package xyz.eden.cloud.common.web.spring;

import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import xyz.eden.cloud.common.web.result.HttpResultSet;
import xyz.eden.cloud.common.web.result.HttpResultSetTool;

import java.util.HashSet;
import java.util.Set;

/**
 * @author lianghongwei02
 * @version 1.0
 * @descriptor
 * @date 2023/3/7 15:40
 */
@RestControllerAdvice(basePackages = {"xyz.eden"}, assignableTypes = HttpGlobalExceptionHandler.class)
public class HttpResultSetHandle implements ResponseBodyAdvice<Object> {

    /**
     * 不支持的类型列表
     * 不支持的类型不会被包装
     */
    private static final Set<Class<?>> NO_SUPPORTED_CLASSES = new HashSet<>(8);

    static {
        NO_SUPPORTED_CLASSES.add(HttpResultSet.class);
        NO_SUPPORTED_CLASSES.add(String.class);
        NO_SUPPORTED_CLASSES.add(byte[].class);
        NO_SUPPORTED_CLASSES.add(Resource.class);
        NO_SUPPORTED_CLASSES.add(javax.xml.transform.Source.class);
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (NO_SUPPORTED_CLASSES.contains(returnType.getParameterType())) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return HttpResultSetTool.builderSuccess(body);
    }
}
